package com.xlh.service.cs.impl;

import com.google.common.collect.Lists;
import com.xlh.dao.cs.WorkPlaceMapper;
import com.xlh.dao.cs.WorkPlaceMapperExt;
import com.xlh.dto.cs.CourseSystemDTO;
import com.xlh.param.cs.CourseSystemParam;
import com.xlh.pojo.cs.WorkPlace;
import com.xlh.pojo.cs.WorkPlaceExample;
import com.xlh.service.cs.CourseSystemWorkPlaceService;
import com.xlh.service.cs.CourseWorkService;
import com.xlh.util.BeanUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhr 2019/10/17
 */
@Service
public class CourseSystemWorkPlaceServiceImpl implements CourseSystemWorkPlaceService {

    @Autowired
    private WorkPlaceMapper mapper;
    @Autowired
    private WorkPlaceMapperExt mapperExt;
    @Autowired
    private CourseWorkService courseWorkService;

    @Override
    public void batchEdit(List<CourseSystemParam> insertList, List<CourseSystemParam> updateList, List<CourseSystemParam> deleteList) {
        if (CollectionUtils.isNotEmpty(insertList))
            batchInsert(insertList);
        if (CollectionUtils.isNotEmpty(updateList))
            batchUpdate(updateList);
        if (CollectionUtils.isNotEmpty(deleteList))
            batchDelete(deleteList);
    }

    @Override
    public List<CourseSystemDTO> listWorkPlace() {
        List<WorkPlace> list = selectList();
        return BeanUtil.batchTransform(CourseSystemDTO.class, list);
    }

    private List<WorkPlace> selectList() {
        WorkPlaceExample example = new WorkPlaceExample();
        example.createCriteria().andDeletedEqualTo(false);
        List<WorkPlace> list = mapper.selectByExample(example);
        return CollectionUtils.isEmpty(list) ? Lists.newArrayList() : list;
    }

    private void batchDelete(List<CourseSystemParam> deleteList) {
        if (CollectionUtils.isEmpty(deleteList)) {
            return;
        }

        List<Long> ids = deleteList.stream().map(CourseSystemParam::getId).collect(Collectors.toList());

        WorkPlaceExample example = new WorkPlaceExample();
        example.createCriteria().andIdIn(ids);

        WorkPlace workPlace = new WorkPlace();
        workPlace.setDeleted(true);

        mapper.updateByExampleSelective(workPlace, example);

        // 删除课程-工作岗位中的对应数据
        courseWorkService.deleteByWorkIds(ids);
    }

    private void batchUpdate(List<CourseSystemParam> updateList) {
        List<WorkPlace> list = BeanUtil.batchTransform(WorkPlace.class, updateList);
        mapperExt.batchUpdate(list);
    }

    private void batchInsert(List<CourseSystemParam> insertList) {
        List<WorkPlace> list = BeanUtil.batchTransform(WorkPlace.class, insertList);
        mapperExt.batchInsert(list);
    }
}
